﻿#include <QFileDialog>
#include "mainwindow.h"

#include <QGraphicsDropShadowEffect>
#include <stdio.h>

#ifdef _WIN64
#pragma comment(lib,"MVCAMSDK_X64.lib")
#else
#pragma comment(lib,"MVCAMSDK.lib")
#endif



MainWindow::MainWindow(QWidget* parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    m_nIndex = 0;

    m_nMesc = 0;
    m_nMinute = 0;
    m_nHour = 0;

    m_pTimer = new QTimer();
    connect(m_pTimer, &QTimer::timeout, this, &MainWindow::onTimerOut);

    ui->gBox_static_1->hide();
    ui->gBox_static_2->hide();
    ui->gBox_static_3->hide();
    ui->gBox_static_4->hide();
    //注册数据类型 不然信号槽会数据丢失
    qRegisterMetaType<CameraData>("CameraData");


    m_algDlg = new AlgDialog(this);
    m_algDlg->hide();

    /* THREAD */
    m_tCamera1 = new CameraThread();
    m_tCamera2 = new CameraThread();
    m_tCamera3 = new CameraThread();


    m_tAlg1 = new AlgThread();
    m_tAlg2 = new AlgThread();
    m_tAlg3 = new AlgThread();

    m_tLAlg << m_tAlg1 << m_tAlg2 << m_tAlg3;
    m_tSaveImg1 = new SaveImgThread();
    m_tSaveImg2 = new SaveImgThread();
    m_tSaveImg3 = new SaveImgThread();

    m_tLSaveImg << m_tSaveImg1 << m_tSaveImg2 << m_tSaveImg3;
    // Connect Camera and Alg Thread event
    connect(m_tCamera1->m_worker, &CameraWorker::sigAlgStart, m_tAlg1->m_worker, &AlgWorker::start);
    connect(m_tCamera2->m_worker, &CameraWorker::sigAlgStart, m_tAlg2->m_worker, &AlgWorker::start);
    connect(m_tCamera3->m_worker, &CameraWorker::sigAlgStart, m_tAlg3->m_worker, &AlgWorker::start);

    connect(m_tAlg1->m_worker, &AlgWorker::sigSaveImgStart, m_tSaveImg1->m_worker, &SaveImgWorker::start);
    connect(m_tAlg2->m_worker, &AlgWorker::sigSaveImgStart, m_tSaveImg2->m_worker, &SaveImgWorker::start);
    connect(m_tAlg3->m_worker, &AlgWorker::sigSaveImgStart, m_tSaveImg3->m_worker, &SaveImgWorker::start);


    connect(m_tAlg1->m_worker, &AlgWorker::sigCameraResult, this, &MainWindow::CameraResult);

    connect(m_algDlg, &AlgDialog::sigAlgToMain, this, &MainWindow::sloAlgInfo);


    QFile file(":/qss/main.qss");
    if (file.open(QFile::ReadOnly))
    {
        QTextStream filetext(&file);
        QString stylesheet = filetext.readAll();
        this->setStyleSheet(stylesheet);
        file.close();
    }

    //内层窗口添加对应的阴影效果
    QGraphicsDropShadowEffect *shadow_effectA = new QGraphicsDropShadowEffect(this);

    shadow_effectA->setOffset(0, 0);
    shadow_effectA->setColor(QColor(150,150,150));
    shadow_effectA->setBlurRadius(6);

    QGraphicsDropShadowEffect *shadow_effectB = new QGraphicsDropShadowEffect(this);

    shadow_effectB->setOffset(0, 0);
    shadow_effectB->setColor(QColor(150,150,150));
    shadow_effectB->setBlurRadius(6);

    ui->gBox_left->setGraphicsEffect(shadow_effectA);
    ui->gBox_top->setGraphicsEffect(shadow_effectB);


    QGraphicsDropShadowEffect *shadow_effectC = new QGraphicsDropShadowEffect(this);

    shadow_effectC->setOffset(0, 0);
    shadow_effectC->setColor(QColor(150,150,150));
    shadow_effectC->setBlurRadius(6);

    ui->tableWidget->setGraphicsEffect(shadow_effectC);


    QGraphicsDropShadowEffect *shadow_effectD = new QGraphicsDropShadowEffect(this);

    shadow_effectD->setOffset(0, 0);
    shadow_effectD->setColor(QColor(150,150,150));
    shadow_effectD->setBlurRadius(6);

    ui->tabWidget->setGraphicsEffect(shadow_effectD);



    m_tCamera1->Initialize();
    m_tCamera2->Initialize();
    m_tCamera3->Initialize();

    CreateCameraSaveFile();
    RdConfig();





    m_timer = new QTimer(this);
    connect(m_timer, SIGNAL(timeout()), this, SLOT(camera_statues()));
    m_timer->start(1000);



    //start task thread



    m_camera_statuesFps = new QLabel(this);
    m_camera_statuesFps->setAlignment(Qt::AlignHCenter);
    ui->statusBar->addWidget(m_camera_statuesFps);

    /* table data */
    ui->tableWidget->setShowGrid(true);
    ui->tableWidget->setSelectionBehavior(QAbstractItemView::SelectRows);
    ui->tableWidget->setSelectionMode(QAbstractItemView::SingleSelection);
    ui->tableWidget->setEditTriggers(QAbstractItemView::NoEditTriggers);
    //自动调整窗口列表的【宽、高】---适应窗口大小
    ui->tableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);

    ui->tableWidget->verticalHeader()->hide();//取消默认行号

    QStringList header;
    header << tr("tag")
           << tr("1")<< tr("2")
           << tr("3")<< tr("4")
           << tr("5")<< tr("6")
           << tr("7")<< tr("8")
           << tr("9")<< tr("10")
           << tr("11")<< tr("12")
           << tr("13")<< tr("14")
           << tr("15")<< tr("16")
           << tr("17")<< tr("18")
           << tr("19")<< tr("20");
    ui->tableWidget->setColumnCount(header.size());
    ui->tableWidget->setHorizontalHeaderLabels(header);

    //允许绘制背景色交替 必须写这句否则交替背景色没有效果
    ui->tableWidget->setAlternatingRowColors(true);
    InitTable();
    //             相机初始化-
    if (init_SDK() == -1) {
        status = 0;
    }
    if(lCamers.size()>0){
        for(int i = 0;i < lCamers.size();i++){
            GUI_init_Resolution(lCamers[i].g_hCamera, &lCamers[i].g_tCapability);
            GUI_init_parameter(lCamers[i].g_hCamera, &lCamers[i].g_tCapability,i);
        }
    }

}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::InitTable()
{
    ui->tableWidget->setRowCount(4); // 设置显示的行数
    ui->tableWidget->setItem(0,0,new QTableWidgetItem(tr("COUNT")));
    ui->tableWidget->setItem(1,0,new QTableWidgetItem(tr("CD1|NG")));
    ui->tableWidget->setItem(2,0,new QTableWidgetItem(tr("CD2|NG")));
    ui->tableWidget->setItem(3,0,new QTableWidgetItem(tr("CD3|NG")));
    ui->tableWidget->item(0,0)->setTextAlignment(Qt::AlignHCenter|Qt::AlignVCenter);
    ui->tableWidget->item(1,0)->setTextAlignment(Qt::AlignHCenter|Qt::AlignVCenter);
    ui->tableWidget->item(2,0)->setTextAlignment(Qt::AlignHCenter|Qt::AlignVCenter);
    ui->tableWidget->item(3,0)->setTextAlignment(Qt::AlignHCenter|Qt::AlignVCenter);
    for(int i=0;i<4;i++){
        for(int j = 1;j<21;j++){
            ui->tableWidget->setItem(i,j,new QTableWidgetItem(QString::number(0)));
            ui->tableWidget->item(i,j)->setTextAlignment(Qt::AlignHCenter|Qt::AlignVCenter);
        }
    }

    for(int i=0;i<20;i++){
        qlCount << 0;
        qlCD1 << 0;
        qlCD2 << 0;
        qlCD3 << 0;
    }
}


void MainWindow::CreateCameraSaveFile()
{
    QDir dir;
    QString imgPath = QDir::currentPath() + "/Pic";
    QString ConfigPath = QDir::currentPath() + "/Config";
    bool img = dir.exists(imgPath);
    bool con = dir.exists(ConfigPath);
    if (!img)
    {
        dir.mkdir(imgPath);

        dir.mkdir(imgPath + "/ccd1");
        dir.mkdir(imgPath + "/ccd1/OK");
        dir.mkdir(imgPath + "/ccd1/NG");
        dir.mkdir(imgPath + "/ccd1/Confuse");
        dir.mkdir(imgPath + "/ccd1/Abnormal");

        dir.mkdir(imgPath + "/ccd2");
        dir.mkdir(imgPath + "/ccd2/OK");
        dir.mkdir(imgPath + "/ccd2/NG");
        dir.mkdir(imgPath + "/ccd2/Confuse");
        dir.mkdir(imgPath + "/ccd2/Abnormal");

        dir.mkdir(imgPath + "/ccd3");
        dir.mkdir(imgPath + "/ccd3/OK");
        dir.mkdir(imgPath + "/ccd3/NG");
        dir.mkdir(imgPath + "/ccd3/Confuse");
        dir.mkdir(imgPath + "/ccd3/Abnormal");

    }
    if (!con)
    {
        dir.mkdir(ConfigPath);
        QFile filename1(ConfigPath + "/config.ini");
        filename1.open(QIODevice::WriteOnly);
        filename1.close();
    }
}



void MainWindow::OpenHalconWindows()
{
    //重置数据

    m_tAlg1->m_worker->m_nResult = 0;
    m_tAlg2->m_worker->m_nResult = 0;
    m_tAlg3->m_worker->m_nResult = 0;


    
    Hlong hWind;
    // Halcon
    if (m_nOpenHalcon) {
        return;
    }
    m_nOpenHalcon = 1;
    hWind = ui->main_ccd1->winId();
    HalconCpp::OpenWindow(0, 0, ui->main_ccd1->width(), ui->main_ccd1->height(), hWind, "", "", &m_hvMainHandle1);

    hWind = ui->main_ccd2->winId();
    HalconCpp::OpenWindow(0, 0, ui->main_ccd2->width(), ui->main_ccd2->height(), hWind, "", "", &m_hvMainHandle2);

    hWind = ui->main_ccd3->winId();
    HalconCpp::OpenWindow(0, 0, ui->main_ccd3->width(), ui->main_ccd3->height(), hWind, "", "", &m_hvMainHandle3);

    hWind = ui->main_ccd4->winId();
    HalconCpp::OpenWindow(0, 0, ui->main_ccd4->width(), ui->main_ccd4->height(), hWind, "", "", &m_hvMainHandle4);



    hWind = ui->frame_ccd1->winId();
    HalconCpp::OpenWindow(0, 0, ui->frame_ccd1->width(), ui->frame_ccd1->height(), hWind, "", "", &c1_hvCCDHandle);

    hWind = ui->frame_ccd2->winId();
    HalconCpp::OpenWindow(0, 0, ui->frame_ccd2->width(), ui->frame_ccd2->height(), hWind, "", "", &c2_hvCCDHandle);

    hWind = ui->frame_ccd3->winId();
    HalconCpp::OpenWindow(0, 0, ui->frame_ccd3->width(), ui->frame_ccd3->height(), hWind, "", "", &c3_hvCCDHandle);

    hWind = ui->frame_ccd4->winId();
    HalconCpp::OpenWindow(0, 0, ui->frame_ccd4->width(), ui->frame_ccd4->height(), hWind, "", "", &c4_hvCCDHandle);




    m_tCamera1->m_worker->m_cData.m_nIndex = 1;
    m_tCamera2->m_worker->m_cData.m_nIndex = 2;
    m_tCamera2->m_worker->m_cData.m_nIndex = 3;



    m_tCamera1->m_worker->m_cData.hv_WindowHandle = m_hvMainHandle1;
    m_tCamera2->m_worker->m_cData.hv_WindowHandle = m_hvMainHandle2;
    m_tCamera3->m_worker->m_cData.hv_WindowHandle = m_hvMainHandle3;



    if(lCamers.size()>0){
        m_tCamera1->start();
        m_tCamera1->m_worker->m_camera = lCamers[0];
        m_tCamera1->m_worker->stream();
    }



    if (lCamers.size() > 1) {
        m_tCamera2->start();
        m_tCamera2->m_worker->m_camera = lCamers[1];
        m_tCamera2->m_worker->stream();
    }

    if (lCamers.size() > 2) {
        m_tCamera3->start();
        m_tCamera3->m_worker->m_camera = lCamers[2];
        m_tCamera3->m_worker->stream();
    }

}


void MainWindow::changeEvent(QEvent* e)
{
    QMainWindow::changeEvent(e);
    switch (e->type()) {
    case QEvent::LanguageChange:
        ui->retranslateUi(this);
        break;
    default:
        break;
    }
}


/*
* 关闭程序处理
*
*
*/

void MainWindow::closeEvent(QCloseEvent* e)
{

    QMainWindow::closeEvent(e);
}




/*
*  相机状态栏
*
*
*/

void MainWindow::camera_statues()
{
    int c1_cfps = m_tCamera1->m_worker->m_camera.g_read_fps;
    int c2_cfps = m_tCamera2->m_worker->m_camera.g_read_fps;
    int c3_cfps = m_tCamera3->m_worker->m_camera.g_read_fps;
    m_camera_statuesFps->setText(QString("Camera1  fps: %1 | Camera2  Cfps: %2 | Camera3  Cfps: %3 ")
                                 .arg(QString::number(c1_cfps, 'f', 2))
                                 .arg(QString::number(c2_cfps, 'f', 2))
                                 .arg(QString::number(c3_cfps, 'f', 2))
                                 );
    m_tCamera1->m_worker->m_camera.g_read_fps = 0;
    m_tCamera2->m_worker->m_camera.g_read_fps = 0;
    m_tCamera3->m_worker->m_camera.g_read_fps = 0;
}



/*
*  图像显示刷新处理
*
*
*/

void MainWindow::CameraResult(int nResult)
{
    // 更新表格数据
    int result1 = 0;
    int result2 = 0;
    int result3 = 0;




    if(nResult < 20){
        //ccd1
        result1 = m_tAlg1->m_worker->m_nNGorOK1[nResult];
        if (result1)
        {
            qlCD1[nResult] += 1;
        }
    }

    if(nResult > 3 && nResult < 24){
        //ccd2
        result2 = m_tAlg2->m_worker->m_nNGorOK2[nResult - 4];
		if (result2)
		{
            qlCD2[nResult - 4] += 1;
		}
    }

    if(nResult > 7 && nResult < 28){
        //ccd3
        result3 = m_tAlg3->m_worker->m_nNGorOK3[nResult - 8];

		if (result3)
		{
            qlCD3[nResult - 8] += 1;
		}
        m_nSum ++;

        if(qlCD1[nResult-8] || qlCD2[nResult-8] || qlCD3[nResult-8]){
            m_nNG ++;
            qlCount[nResult - 8] += 1;
        }else{
            m_nOK ++;
        }
    }
    float fRationOK = 0.0;
    if (m_nOK)
    {
        fRationOK = float(m_nOK) / float(m_nSum);
    }

    float fRationNG = 0.0;
    if (m_nOK)
    {
        fRationNG = float(m_nNG) / float(m_nSum);
    }
    
    ui->Edit_Sum->setText(QString::number(m_nSum));
    ui->Edit_OK_Num->setText(QString::number(m_nOK));
    ui->Edit_NG_Ratio->setText(QString("%1%").arg(fRationOK*100, 0, 'f', 2));
    ui->Edit_NG_Ratio->setText(QString("%1%").arg(fRationNG*100, 0, 'f', 2));
    upTabView(qlCount,qlCD1,qlCD2,qlCD3);
}

void MainWindow::upTabView(QList<int> qlCount, QList<int> qlCD1, QList<int> qlCD2, QList<int> qlCD3)
{

    for (int i = 1;i < 21;i++) {
        ui->tableWidget->item(0, i)->setText(QString::number(qlCount[i - 1]));
        ui->tableWidget->item(1, i)->setText(QString::number(qlCD1[i - 1]));
        ui->tableWidget->item(2, i)->setText(QString::number(qlCD2[i - 1]));
        ui->tableWidget->item(3, i)->setText(QString::number(qlCD3[i - 1]));
    }
}

void MainWindow::clearAllData()
{
    m_tAlg1->m_worker->clearAllData();
    m_tAlg2->m_worker->clearAllData();
    m_tAlg3->m_worker->clearAllData();

    qlCount.clear();
    qlCD1.clear();
    qlCD2.clear();
    qlCD3.clear();
    for(int i=0;i<20;i++){
        qlCount << 0;
        qlCD1 << 0;
        qlCD2 << 0;
        qlCD3 << 0;
    }

    upTabView(qlCount,qlCD1,qlCD2,qlCD3);

    m_nSum = 0;
    m_nNG = 0;
    m_nOK = 0;
    ui->Edit_Sum->setText(QString::number(0));
    ui->Edit_OK_Num->setText(QString::number(0));
    ui->Edit_NG_Ratio->setText("0");
    ui->Edit_NG_Ratio->setText("0");
}


/*
*  SDK等初始化操作
*
*
*/
int MainWindow::init_SDK()
{

    int                     iCameraCounts = 4;
    int                     iStatus = -1;
    tSdkCameraDevInfo       tCameraEnumList[4];

    //sdk初始化  0 English 1中文
    CameraSdkInit(1);

    //枚举设备，并建立设备列表
    CameraEnumerateDevice(tCameraEnumList, &iCameraCounts);

    //没有连接设备
    if (iCameraCounts == 0) {
        return -1;
    }

    for (int i = 0; i < iCameraCounts; i++) {

        CameraInfo cam;
        //相机初始化。初始化成功后，才能调用任何其他相机相关的操作接口
        iStatus = CameraInit(&tCameraEnumList[i], -1, -1, &cam.g_hCamera);

        //初始化失败
        if (iStatus != CAMERA_STATUS_SUCCESS) {
            return -1;
        }
        //获得相机的特性描述结构体。该结构体中包含了相机可设置的各种参数的范围信息。决定了相关函数的参数
        CameraGetCapability(cam.g_hCamera, &cam.g_tCapability);

        cam.g_pRgbBuffer = (unsigned char*)malloc(cam.g_tCapability.sResolutionRange.iHeightMax * cam.g_tCapability.sResolutionRange.iWidthMax * 3);
        cam.g_readBuf = (unsigned char*)malloc(cam.g_tCapability.sResolutionRange.iHeightMax * cam.g_tCapability.sResolutionRange.iWidthMax * 3);

        /*让SDK进入工作模式，开始接收来自相机发送的图像
        数据。如果当前相机是触发模式，则需要接收到
        触发帧以后才会更新图像。    */
        CameraPlay(cam.g_hCamera);

        /*
            设置图像处理的输出格式，彩色黑白都支持RGB24位
        */
        if (cam.g_tCapability.sIspCapacity.bMonoSensor) {
            CameraSetIspOutFormat(cam.g_hCamera, CAMERA_MEDIA_TYPE_MONO8);
        }
        else {
            CameraSetIspOutFormat(cam.g_hCamera, CAMERA_MEDIA_TYPE_RGB8);
        }

        lCamers.append(cam);
    }
    return 0;
}

/*
*  QT界面初始化
*
*
*/


int MainWindow::GUI_init_parameter(int hCamera, tSdkCameraCapbility* pCameraInfo, int index)
{
    GUI_set_Resolution(hCamera, pCameraInfo,index);
    GUI_init_exposure(hCamera, pCameraInfo);

    GUI_init_isp(hCamera, pCameraInfo);

    GUI_init_Trigger(hCamera, pCameraInfo);

    lCamers[index].g_SaveImage_type = 3;

    return 0;
}

// 设置到分辨率
int  MainWindow::GUI_set_Resolution(int hCamera, tSdkCameraCapbility* pCameraInfo, int index)
{

    tSdkImageResolution* pImageSizeDesc = pCameraInfo->pImageSizeDesc;// 预设分辨率选择
    tSdkImageResolution     sResolution;  //获取当前设置到分辨率

    //获得当前预览的分辨率。
    CameraGetImageResolution(hCamera, &sResolution);

    //lCamers[index].g_W_H_INFO.sensor_width = pImageSizeDesc[sResolution.iIndex].iWidth;
    //lCamers[index].g_W_H_INFO.sensor_height = pImageSizeDesc[sResolution.iIndex].iHeight;
    //lCamers[index].g_W_H_INFO.buffer_size = lCamers[index].g_W_H_INFO.sensor_width * lCamers[index].g_W_H_INFO.sensor_height;
    return 1;
}

int  MainWindow::GUI_init_Resolution(int hCamera, tSdkCameraCapbility* pCameraInfo)
{
    int                     i = 0;
    tSdkImageResolution* pImageSizeDesc = pCameraInfo->pImageSizeDesc;// 预设分辨率选择
    int                     iImageSizeDesc = pCameraInfo->iImageSizeDesc; // 预设分辨率的个数，即pImageSizeDesc数组的大小



    return 1;
}

int  MainWindow::GUI_init_Trigger(int hCamera, tSdkCameraCapbility* pCameraInfo)
{
    int  pbySnapMode;
    int StrobeMode = 0;
    int  uPolarity = 0;

    //获得相机的触发模式。
    CameraGetTriggerMode(hCamera, &pbySnapMode);

    //设置相机的触发模式。0表示连续采集模式；1表示软件触发模式；2表示硬件触发模式。
    switch (pbySnapMode) {
    case 0:
        break;
    case 1:
        break;
    case 2:
        CameraGetStrobeMode(hCamera, &StrobeMode);
        CameraGetStrobePolarity(hCamera, &uPolarity);

        if (StrobeMode) {
            CameraSetStrobePolarity(hCamera, 1);
            if (uPolarity) {
                CameraSetStrobePolarity(hCamera, 1);
            }
            else {
                CameraSetStrobePolarity(hCamera, 0);
            }
        }
        else {
            CameraSetStrobePolarity(hCamera, 0);
        }
        break;
    default:
        break;
    }
    return 1;
}


int  MainWindow::GUI_init_exposure(int hCamera, tSdkCameraCapbility* pCameraInfo)
{

    BOOL            AEstate = FALSE;
    int             pbyAeTarget;
    double          pfExposureTime;
    int             pusAnalogGain;
    BOOL            FlickEnable = FALSE;
    int             piFrequencySel;
    double	        m_fExpLineTime = 0;//当前的行曝光时间，单位为us
    tSdkExpose* SdkExpose = &pCameraInfo->sExposeDesc;

    //获得相机当前的曝光模式。
    CameraGetAeState(hCamera, &AEstate);

    //获得自动曝光的亮度目标值。
    CameraGetAeTarget(hCamera, &pbyAeTarget);

    //获得自动曝光时抗频闪功能的使能状态。
    CameraGetAntiFlick(hCamera, &FlickEnable);

    //获得相机的曝光时间。
    CameraGetExposureTime(hCamera, &pfExposureTime);

    //获得图像信号的模拟增益值。
    CameraGetAnalogGain(hCamera, &pusAnalogGain);

    //获得自动曝光时，消频闪的频率选择。
    CameraGetLightFrequency(hCamera, &piFrequencySel);

    /*
    获得一行的曝光时间。对于CMOS传感器，其曝光
    的单位是按照行来计算的，因此，曝光时间并不能在微秒
    级别连续可调。而是会按照整行来取舍。这个函数的
    作用就是返回CMOS相机曝光一行对应的时间。
*/
    CameraGetExposureLineTime(hCamera, &m_fExpLineTime);
    exposure_time_lineedit_status = false;
    if (!AEstate) {
        //设置相机曝光的模式。自动或者手动。关
        CameraSetAeState(hCamera, false);
    }
    else {
        //设置相机曝光的模式。自动或者手动。开
        CameraSetAeState(hCamera, true);
        if (FlickEnable) {
            //设置自动曝光时抗频闪功能的使能状态。对于手动曝光模式下无效。
            CameraSetAntiFlick(hCamera, true);
            if (piFrequencySel) {
                //设置自动曝光时消频闪的频率。0:50HZ , 1:60HZ
                CameraSetLightFrequency(hCamera, piFrequencySel);
            }
            else {
                CameraSetLightFrequency(hCamera, piFrequencySel);
            }
        }
        else {
            CameraSetAntiFlick(hCamera, false);

            if (piFrequencySel) {
                //设置自动曝光时消频闪的频率。0:50HZ , 1:60HZ
                CameraSetLightFrequency(hCamera, piFrequencySel);
            }
            else {
                CameraSetLightFrequency(hCamera, piFrequencySel);
            }
        }
    }
    return 1;
}


int  MainWindow::GUI_init_isp(int hCamera, tSdkCameraCapbility* pCameraInfo)
{
    BOOL        m_bHflip = FALSE;
    BOOL        m_bVflip = FALSE;
    int         m_Sharpness = 0;

    tSharpnessRange* SharpnessRange = &pCameraInfo->sSharpnessRange;
    //获得图像的镜像状态。
    CameraGetMirror(hCamera, MIRROR_DIRECTION_HORIZONTAL, &m_bHflip);
    CameraGetMirror(hCamera, MIRROR_DIRECTION_VERTICAL, &m_bVflip);
    //获取当前锐化设定值。
    CameraGetSharpness(hCamera, &m_Sharpness);
    return 1;
}


/*
*  QT界面按钮等操作
*
*
*/


void MainWindow::on_Bt_implement_clicked()
{
    //m_tCamera1->start();
    OpenHalconWindows();
    if(m_nImplement == 0){
        m_tAlg1->m_worker->m_nImplement = 1;
        m_tAlg2->m_worker->m_nImplement = 1;
        m_tAlg3->m_worker->m_nImplement = 1;
        ui->Bt_implement->setText(QStringLiteral("停止检测"));
        m_pTimer->start(1000);
    }else{
        m_tAlg1->m_worker->m_nImplement = 0;
        m_tAlg2->m_worker->m_nImplement = 0;
        m_tAlg3->m_worker->m_nImplement = 0;
        ui->Bt_implement->setText(QStringLiteral("执行检测"));
        m_pTimer->stop();
        clearAllData();
    }
    m_nImplement = 1 - m_nImplement;
}


void MainWindow::on_tabWidget_currentChanged(int index)
{
    switch (index)
    {
    case 0:
        m_tCamera1->m_worker->m_cData.hv_WindowHandle = m_hvMainHandle1;
        m_tCamera2->m_worker->m_cData.hv_WindowHandle = m_hvMainHandle2;
        m_tCamera3->m_worker->m_cData.hv_WindowHandle = m_hvMainHandle3;
        break;
    case 1:
        m_tCamera1->m_worker->m_cData.hv_WindowHandle = c1_hvCCDHandle;
        break;
    case 2:
        m_tCamera2->m_worker->m_cData.hv_WindowHandle = c2_hvCCDHandle;
        break;
    case 3:
        m_tCamera3->m_worker->m_cData.hv_WindowHandle = c3_hvCCDHandle;
        break;
    default:
        break;
    }
}



void MainWindow::on_checkBox_NG_clicked(bool checked)
{
    for (int i=0;i<3;i++) {
        if (checked) {
            m_tLSaveImg[i]->m_worker->m_nSaveType += 10;
            m_tLAlg[i]->m_worker->m_nSave += 10;
        }
        else {
            m_tLSaveImg[i]->m_worker->m_nSaveType -= 10;
            m_tLAlg[i]->m_worker->m_nSave -= 10;
        }
    }
}


void MainWindow::on_checkBox_OK_clicked(bool checked)
{
    for (int i=0;i<3;i++) {
        if (checked) {
            m_tLSaveImg[i]->m_worker->m_nSaveType += 1;
            m_tLAlg[i]->m_worker->m_nSave += 1;
        }
        else {
            m_tLSaveImg[i]->m_worker->m_nSaveType -= 1;
            m_tLAlg[i]->m_worker->m_nSave -= 1;
        }
    }
}


void MainWindow::on_checkBox_BJ_clicked(bool checked)
{
    for (int i=0;i<3;i++) {
        if (checked) {
            m_tLSaveImg[i]->m_worker->m_nSaveType += 100;
            m_tLAlg[i]->m_worker->m_nSave += 100;
        }
        else {
            m_tLSaveImg[i]->m_worker->m_nSaveType -= 100;
            m_tLAlg[i]->m_worker->m_nSave -= 100;
        }
    }
}


void MainWindow::on_pushButton_4_clicked()
{
    m_algDlg->show();
    m_algDlg->m_part = m_impurity;
    m_algDlg->ViewsInit();
}



void MainWindow::OpenFileImg(int index)
{
    QString OpenFile;
    //打开文件夹中的图片文件
    OpenFile = QFileDialog::getOpenFileName(this,
                                            "Please choose an image file",
                                            "",
                                            "Image Files(*.jpg *.png *.bmp *.pgm *.pbm);;All(*.*)");
    if (OpenFile != "")
    {

        //OpenHalconWindows();

        // 获取当前文件所有图片名称
        QFileInfo fi;
        QString file_name;
        QString file_path;
        QStringList file_list;
        int file_index = 0;
        fi = QFileInfo(OpenFile);
        file_name = fi.fileName();
        file_path = fi.absolutePath();

        QDir dir(file_path);
        file_list = dir.entryList(QDir::Files | QDir::NoDotAndDotDot);
        file_index = file_list.indexOf(file_name);

        m_vFilePath[index] = file_path;
        m_vFileList[index] = file_list;
        m_vFileIndex[index] = file_index;

        CarouselImage(index);

    }
}

void MainWindow::CarouselImage(int index)
{
    QString OpenFile = QString("%1/%2").arg(m_vFilePath[index]).arg(m_vFileList[index][m_vFileIndex[index]]);

    QTextCodec *code = QTextCodec::codecForName("GB2312");//解决中文路径问题
    std::string name = code->fromUnicode(OpenFile).data();

    HalconCpp::ReadImage(&m_hImage, name.c_str());

    switch (index) {
    case 1:
        m_hvHandle = m_hvMainHandle1;
        //m_tAlg1->m_worker->imgA = m_hImage;

        break;
    case 2:
        m_hvHandle = m_hvMainHandle2;
        //m_tAlg1->m_worker->imgB = m_hImage;
        break;
    }
    m_tAlg1->m_worker->show(m_hImage, m_hvHandle, 0);
}

void MainWindow::RdConfig()
{
    QString iniFilePath = "Config/config.ini";
    QSettings configIniRead(iniFilePath, QSettings::IniFormat);
    configIniRead.setIniCodec(QTextCodec::codecForName("UTF_8"));
    QString sInfo;
    int* pData;
    for(int tag=0;tag<3;tag++){
        pData = &m_tLAlg[tag]->m_worker->m_algImpurity.m_part.parameter1;
        for(int i=0;i<10;i++){
            sInfo = QString("AlgPart_%1/part%2").arg(tag+1).arg(i+1);
            *pData = configIniRead.value(sInfo).toInt();
            pData++;
        }
    }

}

void MainWindow::sloAlgInfo(int nIndx)
{
    switch (nIndx)
    {
    case 1:
    case 2:
        OpenFileImg(nIndx);
        break;
    case 3:
        RdConfig();
        break;
    case 4:
        /*int result = m_tAlg1->m_worker->CCD_Alg(m_tAlg1->m_worker->imgA, m_tAlg1->m_worker->imgB,1);
        if (result>0)
        {
            m_hImage = m_tAlg1->m_worker->m_algImpurity.ho_ImageResult;
        }
        m_tAlg1->m_worker->show(m_hImage, m_hvHandle, result);*/
        break;
    }
}

void MainWindow::onTimerOut()
{
    ui->timeNumber->display(GetRunTime());
}

void MainWindow::appQuit()
{
    m_tCamera1->m_worker->pause();
    m_tCamera2->m_worker->pause();
    m_tCamera3->m_worker->pause();
    Sleep(1000 * lCamers.size());
    for (int i = 0; i < lCamers.size(); i++) {
        if (lCamers[i].g_readBuf != NULL) {
            free(lCamers[i].g_readBuf);
            lCamers[i].g_readBuf = NULL;
        }

        if (lCamers[i].g_pRgbBuffer != NULL) {
            free(lCamers[i].g_pRgbBuffer);
            lCamers[i].g_pRgbBuffer = NULL;
        }

        if (lCamers[i].g_hCamera > 0) {
            //相机反初始化。释放资源。
            CameraUnInit(lCamers[i].g_hCamera);
            lCamers[i].g_hCamera = -1;
        }
    }
}

QString MainWindow::GetRunTime()
{
    m_nMesc += 1;
    if(m_nMesc == 60){
        m_nMesc = 0;
        m_nMinute += 1;
    }
    if(m_nMinute == 60){
        m_nMinute = 0;
        m_nHour += 1;
    }
    return QString("%1-%2 %3")
            .arg(m_nHour, 4, 10, QLatin1Char('0'))
            .arg(m_nMinute, 2, 10, QLatin1Char('0'))
            .arg(m_nMesc, 2, 10, QLatin1Char('0'));
}
